﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using WaterRegimenMonitor.Common;
using WaterRegimenMonitor.Web.Domain;

namespace WaterRegimenMonitor.Web.Models.Common
{
    /// <summary>
    /// 菜单视图模型
    /// </summary>
    public class MenuViewModel
    {
        /// <summary>
        /// 获得菜单HTML。
        /// </summary>
        /// <returns></returns>
        public string GetMenuHtml()
        {
            //用于保存菜单数据
            StringBuilder builder = new StringBuilder();

            //获得菜单列表
            var list = Helper.CurrentPrincipal.MenuList;

            //判断菜单列表是否存在
            if (list == null || list.Count == 0)
            {
                return string.Empty;
            }

            //用于保存分类序号
            int categoryIndex = 0;

            //循环生成菜单HTML
            for (int i = 0; i < list.Count; i++)
            {
                MenuInfo next = null;
                MenuInfo current = list[i];
                MenuInfo previous = null;

                if (i > 0)
                {
                    previous = list[i - 1];
                }
                if (i < list.Count - 1)
                {
                    next = list[i + 1];
                }

                bool firstRow = false;
                bool lastRow = false;
                string menuClass = string.Empty;

                //判断是否为第一个分类
                if (previous == null || (current.Category.CategoryID != previous.Category.CategoryID))
                {
                    //增加分类序号
                    categoryIndex++;

                    //添加菜单分类
                    builder.AppendFormat("<div id=\"{0}\"><p><span>{1}</span><span class='menuRightButton menuRightButtonUp' data-group='{2}'></span></p></div>", previous == null ? "menutitle_first" : "menutitle", list[i].Category.CategoryName, categoryIndex);

                    //设置为是第一行
                    firstRow = true;
                }

                //判断是否为此分类的最后一行
                if (next == null || (current.Category.CategoryID != next.Category.CategoryID))
                {
                    lastRow = true;
                }

                if (firstRow)
                {
                    builder.AppendFormat("<ul data-group='{0}'>", categoryIndex);
                }

                if (firstRow || lastRow)
                {
                    menuClass = string.Format(" class=\"{0}\"", ((firstRow && lastRow) ? "last first" : (firstRow ? "first" : "last")));
                }

                builder.AppendFormat("<li{0}><a href=\"{1}\">{2}</a></li>", menuClass, current.Menu.SourceUrl, current.Menu.MenuName);

                if (lastRow)
                {
                    builder.Append("</ul>");
                }
            }

            return builder.ToString();
        }
    }
}